<template>
  <div class="form-container">
    <el-row type="flex" justify="center">
      <el-form style="width:100%;" ref="form" :model="form" :rules="formRules" label-position="left" label-width="80px">
        <!-- 权限名称 -->
        <el-row type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('permission.name')" prop="name">
              <el-input v-model="form.name" :placeholder="$t('input')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 权限描述 -->
        <el-row type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('permission.title')" prop="title">
              <el-input v-model="form.title" :placeholder="$t('input')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 附加条件 -->
        <el-row type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('permission.condition')" prop="condition">
              <el-input v-model="form.condition" :placeholder="$t('input')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 父权限id -->
        <el-row type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('permission.pid')" prop="pid">
              <el-select
                v-model="form.pid" 
                name="pid" 
                :placeholder="$t('select')"
                style="width:100%;">
                <el-option v-for="permission in allTopLevelPermissions" :label="permission.name" :value="permission.permission_id" :key="permission.permission_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 提交 -->
        <el-row type="flex" justify="center">
          <el-button :loading="submitLoading" type="primary" @click.native.prevent="onSubmit">{{$t('submit')}}</el-button>
        </el-row>
      </el-form>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'PermissionForm',
  data() {
    return {
      form: {
        name: '',
        title: '',
        pid: '',
        condition: ''
      },
      // form 校验规则
      formRules: {
        name: [{
            required: true,
            trigger: "blur",
            message: this.$t("fieldRequired")
        }],
        pid: [{
            required: true,
            trigger: "blur",
            message: this.$t("fieldRequired")
        }],
      },
      // 组件中的loading遮罩层对象，调用openFullScreenLoading方法时赋值
      loading: null,
      submitLoading: false,
      // 权限数据的树列表数据
      // permissionTree: [],
      // 保存所有第一层的权限
      allTopLevelPermissions: [{
        name: '第一层权限',
        title: '没有父节点',
        permission_id: 0
      }],
      // 编辑中的权限对象
      permission: null,
      // url的权限id参数
      permissionID: this.$route.query.permissionID
    }
  },
  created: function() {
    this.init()
  },
  methods: {
    /**
     * 组件初始化方法
     */
    init() {
      this.initEditPermission()
    },
    onSubmit() {
      // this.$message('submit!')
      this.$refs.form.validate(valid => {
        if (valid) {
          this.addOrUpdatePermission()
        }
      })
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    },
    /**
     * 编辑权限初始化
     */
    initEditPermission() {
      this.openFullScreenLoading()

      const promises = []
      if (this.permissionID) {
        promises.push(this.getPermissionDetailByID(this.permissionID))
        promises.push(this.getAllPermissionList())
      } else {
        promises.push(this.getAllPermissionList())
      }
      Promise.all(promises).then(datas => {
        if (Array.isArray(datas)) {
          if (datas.length === 2) {
            this.processPermissionDetail(datas[0])
            this.processPermissionListData(datas[1])
          } else if (datas.length === 1) {
            this.processPermissionListData(datas[0])
          }
        }

        this.closeFullScreenLoading()
      }).catch(error => {
        this.closeFullScreenLoading()

        console.error('init edit permission has error:', error)
        this.$notify.error({
          title: this.$t('operationFailed'),
          message: this.$t('errorTips'),
        })
      }) 
    },
    /**
     * 根据id获取权限详情
     */
    getPermissionDetailByID(id) {
      return this.$store
        .dispatch('getRolePermissionByID', {id})
    },
    /**
     * 处理权限详情
     */
    processPermissionDetail(data) {
      if (data && data['code'] === 0) {
        const permissionData = data['data']

        if (permissionData) {
          this.permission = permissionData
          const { name, title, pid, permission_id } = this.permission
          this.form.name = name
          this.form.title = title
          this.form.pid = pid
          this.form.permission_id = permission_id
        } 
      } else {
        this.$notify({
          title: this.$t('operationFailed'),
          message: data['msg'],
          type: 'warning'
        })
      }
    },
    /**调用api，提交权限 */
    addOrUpdatePermission() {
      this.submitLoading = true
      let promise
      
      if (this.permissionID) {
        promise = this.$store
          .dispatch('updateOneRolePermission', this.form)
      } else {
        promise = this.$store
          .dispatch('addOneRolePermission', this.form)
      }
      
      if (promise) {
        promise.then(data => {
          this.submitLoading = false;
          if (data && data['code'] === 0) {
            this.$notify({
              title: this.$t('operationSuccess'),
              message: data['msg'],
              type: 'success'
            })
          } else {
            this.$notify({
              title: this.$t('operationFailed'),
              message: data['msg'],
              type: 'warning'
            })
          }

          this.goToPermissionManagement()
        }).catch((error) => {
          console.error('add or update role permission has error:', error)
          this.submitLoading = false;
          this.$notify.error({
            title: this.$t('operationFailed'),
            message: this.$t('errorTips'),
          })
        })
      }
    },
    /**
     * 调用api，获取所有权限
     */
    getAllPermissionList() {
      return this.$store
        .dispatch('getRolePermissionList')
    },
    /**
     * 处理权限数据
     */
    processPermissionListData(data) {
      if (data && data['code'] === 0) {
        const permissionDatas = data['data']

        if (Array.isArray(permissionDatas) && permissionDatas.length > 0) {
          for (const item of permissionDatas) {
            const permissionTemp = {
              name: item.name,
              title: item.title,
              permission_id: item.permission_id
            }
            this.allTopLevelPermissions.push(permissionTemp)
          }
        }
      }
    },
    /**
     * 跳转到权限管理页面
     */
    goToPermissionManagement() {
      this.$router.push({ path: '/permission' })
    },
    /**
     * 显示loading遮罩层
     */
    openFullScreenLoading() {
      this.loading = this.$loading({
        lock: true,
        text: this.$t('loading') + '...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    /**
     * 关闭loading遮罩层
     */
    closeFullScreenLoading() {
      if (this.loading) {
        this.loading.close()
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "@/styles/variables.scss";
@import "../../styles/form-public";
</style>

